//
//  YyxLocationManger.m
//  YyxLocationManger
//
//  Created by imac on 15/6/29.
//  Copyright (c) 2015年 imac. All rights reserved.
//

#import "YyxLocationManger.h"


@interface YyxLocationManger () <CLLocationManagerDelegate>

@property (nonatomic, strong) LocationBlock locationBlock;
@property (nonatomic, strong) NSStringBlock cityBlock;
@property (nonatomic, strong) NSStringBlock addressBlock;
@property (nonatomic, strong) LocationErrorBlock errorBlock;


/**
 *  核心定位类
 */
@property (strong, nonatomic) CLLocationManager *locationManager;


@end


@implementation YyxLocationManger


+ (YyxLocationManger *)shareLocation;
{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init];
    });
    return _sharedObject;
}

- (id)init {
    self = [super init];
    if (self) {
        NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
        
        float longitude = [standard floatForKey:YyxLastLongitude];
        float latitude = [standard floatForKey:YyxLastLatitude];
        self.longitude = longitude;
        self.latitude = latitude;
        self.lastCoordinate = CLLocationCoordinate2DMake(longitude,latitude);
        self.lastCity = [standard objectForKey:YyxLastCity];
        self.lastAddress=[standard objectForKey:YyxLastAddress];
        
        self.locationManager = [[CLLocationManager alloc] init];
        [self.locationManager setDelegate:self];
        if (YyxIOS8) {
            [self.locationManager requestWhenInUseAuthorization];
        }
        [self.locationManager startUpdatingLocation];
    }
    return self;
}

-(NSString *)getLastCity{
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    return [standard objectForKey:YyxLastCity];
}

- (void) getLocationCoordinate:(LocationBlock) locaiontBlock error:(LocationErrorBlock) errorBlock
{
    self.locationBlock = [locaiontBlock copy];
    self.errorBlock = [errorBlock copy];
    [self startLocation];
}

- (void) getLocationCoordinate:(LocationBlock) locaiontBlock  withAddress:(NSStringBlock) addressBlock error:(LocationErrorBlock) errorBlock
{
    self.locationBlock = [locaiontBlock copy];
    self.addressBlock = [addressBlock copy];
    self.errorBlock = [errorBlock copy];
    [self startLocation];
}

- (void) getAddress:(NSStringBlock)addressBlock error:(LocationErrorBlock) errorBlock
{
    self.addressBlock = [addressBlock copy];
    self.errorBlock = [errorBlock copy];
    [self startLocation];
}

- (void) getCity:(NSStringBlock)cityBlock error:(LocationErrorBlock) errorBlock
{
    self.cityBlock = [cityBlock copy];
    self.errorBlock = [errorBlock copy];
    [self startLocation];
}


-(void)startLocation
{
    [self.locationManager startUpdatingLocation];
    [self.locationManager setDelegate:self];
}

-(void)stopLocation
{
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
}


/**
 *  地理位置代理
 *
 *  @param manager   位置管理类
 *  @param locations 经纬度
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation *latestLocation = [locations firstObject];
    _lastCoordinate = latestLocation.coordinate;
    
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    
    [standard setObject:@(self.lastCoordinate.longitude) forKey:YyxLastLongitude];
    [standard setObject:@(self.lastCoordinate.latitude) forKey:YyxLastLatitude];
    
    
    //根据经纬度解析成位置
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:latestLocation completionHandler:^(NSArray *placemark,NSError *error){
        if (error == nil) {
            
            for (CLPlacemark * placeMark in placemark)
            {
                NSDictionary *addressDic=placeMark.addressDictionary;
                
//                NSString *state=[addressDic objectForKey:@"State"];
                NSString *city=[addressDic objectForKey:@"City"];
//                NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
//                NSString *street=[addressDic objectForKey:@"Street"];
                
                self.lastCity = city;
                
                NSString *locatedAt = [[placeMark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
                
                self.lastAddress=locatedAt;
                
                
                NSString *cityName = self.lastCity;
                if([self.lastCity hasSuffix:@"市"]){
                    cityName = [self.lastCity substringToIndex:[self.lastCity length] - 1];
                }
                [standard setObject:cityName forKey:YyxLastCity];
                [standard setObject:self.lastAddress forKey:YyxLastAddress];
                
                [self stopLocation];
            }
            
            if (_cityBlock) {
                _cityBlock(_lastCity);
                _cityBlock = nil;
            }
            
            if (_locationBlock) {
                _locationBlock(_lastCoordinate);
                _locationBlock = nil;
            }
            
            if (_addressBlock) {
                _addressBlock(_lastAddress);
                _addressBlock = nil;
            }
            
            
        } else {
            
            if (_errorBlock) {
                 _errorBlock(error);
            }
           
        }
    }];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.locationManager stopUpdatingLocation];
    [self.locationManager setDelegate:nil];
}

/**
 *  GPS定位失败
 *
 *  @param manager 位置管理类
 *  @param error   错误信息
 */
- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    if (_errorBlock) {
        _errorBlock(error);
    }
    
    [manager stopUpdatingLocation];
}



@end
